package logic

import (
	"context"
	"errors"
	"home-furnish/models/mysql"

	"home-furnish/homerpc/homerpc"
	"home-furnish/homerpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HomeAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHomeAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HomeAddLogic {
	return &HomeAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *HomeAddLogic) HomeAdd(in *homerpc.HomeAddRequest) (*homerpc.HomeAddResponse, error) {
	// todo: add your logic here and delete this line

	brand := mysql.Brand{
		Name: in.BrandName,
	}

	if err := brand.FindBrandByName(mysql.DB, in.BrandName); err != nil {
		return nil, errors.New("品牌已存在")
	}

	class := mysql.Class{
		Name: in.ClassName,
	}

	if err := class.FindClassByName(mysql.DB, in.ClassName); err != nil {
		return nil, errors.New("分类已存在")
	}

	home := mysql.Home{
		Name:    in.Name,
		Image:   in.Image,
		Price:   float64(in.Price),
		ClassId: int64(class.ID),
		BrandId: int64(brand.ID),
	}

	if err := home.HomeAdd(mysql.DB); err != nil {
		return nil, err
	}
	return &homerpc.HomeAddResponse{
		HomeId: int64(home.ID),
	}, nil
}
